import os
from utils.common import CommonUtils

class ConfigManager:
    def __init__(self, task_name):
        self.task_name = task_name
        self.config_file = os.path.join('taskconfig', f'{task_name}.yaml')
        self.config = None
        
    def load_config(self):
        """
        加载配置文件
        """
        if not os.path.exists(self.config_file):
            raise FileNotFoundError(f"配置文件不存在: {self.config_file}")
        
        self.config = CommonUtils.read_yaml_file(self.config_file)
        
        # 验证配置文件结构
        self._validate_config()
        
        # 处理KingbaseES的模式名（转换为小写）
        if 'schema' in self.config['target_db']:
            self.config['target_db']['schema'] = CommonUtils.convert_case_to_lower(
                self.config['target_db']['schema']
            )
            
        # 处理KingbaseES的数据库名（转换为小写）
        self.config['target_db']['database'] = CommonUtils.convert_case_to_lower(
            self.config['target_db']['database']
        )
        
        return self.config
    
    def _validate_config(self):
        """
        验证配置文件结构
        """
        required_sections = ['source_db', 'target_db', 'migration']
        
        for section in required_sections:
            if section not in self.config:
                raise ValueError(f"配置文件缺少必要部分: {section}")
        
        # 验证source_db配置
        source_required = ['host', 'port', 'user', 'password', 'database']
        for key in source_required:
            if key not in self.config['source_db']:
                raise ValueError(f"源数据库配置缺少必要参数: {key}")
        
        # 验证target_db配置
        target_required = ['host', 'port', 'user', 'password', 'database', 'schema']
        for key in target_required:
            if key not in self.config['target_db']:
                raise ValueError(f"目标数据库配置缺少必要参数: {key}")
        
        # 验证migration配置
        if 'batch_size' not in self.config['migration']:
            self.config['migration']['batch_size'] = 1000
        
        if 'skip_existing_tables' not in self.config['migration']:
            self.config['migration']['skip_existing_tables'] = False
        
        if 'include_tables' not in self.config['migration']:
            self.config['migration']['include_tables'] = []
        
        if 'exclude_tables' not in self.config['migration']:
            self.config['migration']['exclude_tables'] = []
        
        if 'export_view_sql' not in self.config['migration']:
            self.config['migration']['export_view_sql'] = True
    
    def get_source_db_config(self):
        """
        获取源数据库配置
        """
        if not self.config:
            self.load_config()
        return self.config['source_db']
    
    def get_target_db_config(self):
        """
        获取目标数据库配置
        """
        if not self.config:
            self.load_config()
        return self.config['target_db']
    
    def get_migration_config(self):
        """
        获取迁移配置
        """
        if not self.config:
            self.load_config()
        return self.config['migration']